<template>
    <div style="height: 100%">
        <a-split :style="{ height: '100%', width: '100%' }" default-size="0.2" min="100px">
            <template #first>
                <div style="padding: 8px 8px 5px 8px">
                    <a-input-search v-model="searchStableName" placeholder="搜索" @search="getStableList"
                                    @press-enter="getStableList"/>
                </div>
                <div>
                    <a-menu>
                        <a-menu-item v-for="(stable,index) in stableList" :key="String(index)" @click="selectStable(stable)">
                            <a-row>
                                <a-col :span="22">
                                    {{ stable }}
                                </a-col>
                                <a-col :span="2">
                                    <a-dropdown @select="selectStableOption" trigger="hover">
                                        <icon-more/>
                                        <template #content>
                                            <a-doption :value="{ option: 'sql',stable:stable }">建表语句</a-doption>
                                            <a-doption :value="{ option: 'describe',stable:stable }">表结构</a-doption>
                                            <a-doption :value="{ option: 'del',stable:stable }">删除表</a-doption>
                                        </template>
                                    </a-dropdown>
                                </a-col>
                            </a-row>
                        </a-menu-item>
                    </a-menu>

                </div>
            </template>
            <template #second>
                <div style="padding: 8px 8px 0 8px">
                    <a-space>
                        <a-range-picker
                                show-time
                                :placeholder="['开始时间','结束时间']"
                                :time-picker-props="{ defaultValue: ['00:00:00', '09:09:06'] }"
                                format="YYYY-MM-DD HH:mm:ss"
                                v-model="queryParam.time"
                        />
                        <a-select v-model="queryParam.order" :disabled="!queryParam.stableName">
                            <a-option value="ASC">时间正序</a-option>
                            <a-option value="DESC">时间倒序</a-option>
                        </a-select>
                        <a-button type="primary" @click="queryDataList" :disabled="!queryParam.stableName">
                            <template #icon>
                                <icon-search/>
                            </template>
                            查询
                        </a-button>
                    </a-space>
                </div>
                <div style="padding: 8px;height: calc(100% - 60px)">
                    <a-table :columns="columns" :data="data" column-resizable :bordered="{cell:true}"
                             :scroll="{x: '100%',y: '100%'}" :scrollbar="true" :pagination="paginationProp"
                             :size="'small'" @page-change="pageChange" @page-size-change="pageSizeChange"></a-table>
                </div>
            </template>
        </a-split>

        <stable-describe-modal ref="stableDescribeModal"></stable-describe-modal>

    </div>
</template>

<script setup lang="ts">

import {onActivated, reactive, ref} from "vue";
import {doQuery} from "../../scripts/mapper";
import {QueryResult} from "../../scripts/type";
import {Message, Modal} from "@arco-design/web-vue";
import StableDescribeModal from "./modal/StableDescribeModal.vue";

const searchStableName = ref('')
const stableList:any[] = reactive([])

const columns:any[] = reactive([]);
const data:any[] = reactive([]);

const stableDescribeModal = ref()

const queryParam = reactive({
    stableName: '',
    time: [],
    order: 'ASC'
})

const paginationProp = reactive({
    total: 0,
    current: 1,
    pageSize: 10,
    showTotal: true,
    showPageSize: true
})

const pageChange = (value) => {
    paginationProp.current = value;
    queryDataList()
}

const pageSizeChange = (value) => {
    paginationProp.current = 1
    paginationProp.pageSize = value;
    queryDataList()
}

onActivated(() => {
    getStableList()
})

const selectStableOption = (value) => {
    switch (value.option) {
        case "sql": {
            showCreateSql(value.stable)
            break;
        }
        case "describe": {
            showDescribe(value.stable)
            break;
        }
        case "del": {
            deleteStable(value.stable)
            break;
        }
    }
}

const deleteStable = (stable) => {
    Modal.warning({
        simple: true,
        hideCancel: false,
        title: '删除超级表',
        content: '确定要删除超级表' + stable + '吗?',
        onOk: () => {
            doQuery("DROP STABLE IF EXISTS " + stable + ";").then((queryResult: QueryResult) => {
                if (queryResult.success && queryResult.data) {
                    Message.success(stable + " 已删除");
                    if (queryParam.stableName === stable) {
                        queryParam.stableName = ''
                        columns.splice(0, columns.length);
                        data.splice(0, data.length);
                    }
                    getStableList();
                } else {
                    Message.error("删除失败" + (queryResult.message ? (": " + queryResult.message) : ""))
                }
            })
        }
    });
}

const showDescribe = (stable) => {
    stableDescribeModal.value.show(stable)
}

const showCreateSql = (stable) => {
    doQuery("SHOW CREATE STABLE " + stable + ";").then((queryResult: QueryResult) => {
        if (queryResult.success && queryResult.data) {
            Modal.open({
                title: queryResult.data[0][0] + ' 建表语句',
                content: String(queryResult.data[0][1]),
                hideCancel: true
            });
        } else {
            Message.error("建表语句查询失败" + (queryResult.message ? (": " + queryResult.message) : ""))
        }
    })
}

const getStableList = () => {
    doQuery("SHOW STABLES " + (searchStableName.value ? ("LIKE '%" + searchStableName.value + "%'") : "") + ";").then((queryResult: QueryResult) => {
        if (queryResult.success && queryResult.data) {
            stableList.splice(0, stableList.length)
            queryResult.data.forEach(item => stableList.push(item[0]))
        } else {
            Message.error("查询超级表失败" + (queryResult.message ? (": " + queryResult.message) : ""))
        }
    })
}

const selectStable = (tableName) => {
    queryParam.stableName = tableName;
    paginationProp.current = 1
    paginationProp.pageSize = 10
    queryDataList()
}

const queryDataList = () => {
    if (!queryParam.stableName) {
        return
    }
    let condition = queryParam.stableName

    if (queryParam.time && queryParam.time.length > 0) {
        condition += " WHERE"
        condition += (" ts >= '" + queryParam.time[0] + "'")
        condition += " AND"
        condition += (" ts <= '" + queryParam.time[1] + "'")
    }

    doQuery("SELECT COUNT(*) FROM " + condition + ";").then((queryResult) => {
        if (queryResult.success && queryResult.data) {
            paginationProp.total =  queryResult.data.length > 0 ? queryResult.data[0][0] : 0
            condition += (" ORDER BY ts " + queryParam.order)
            condition += (" LIMIT " + (paginationProp.current - 1) * paginationProp.pageSize + "," + paginationProp.pageSize)
            queryData(condition);
        }
    })
}


const queryData = (condition) => {
    doQuery("SELECT * FROM " + condition + ";").then((queryResult) => {
        if (queryResult.success && queryResult.data) {
            columns.splice(0, columns.length);
            data.splice(0, data.length);
            queryResult.meta?.forEach((metaItem) => {
                columns.push({
                    title: metaItem.columnName,
                    dataIndex: metaItem.columnName,
                    width: 120
                })
            })
            queryResult.data?.forEach((dataItem: any) => {
                let dataObj = {};
                queryResult.meta?.forEach((metaItem, index) => {
                    dataObj[metaItem.columnName!] = dataItem[index]
                })
                data.push(dataObj)
            })
        }
    })
}


</script>

<style>
.arco-dropdown-open .arco-icon-down {
    transform: rotate(180deg);
}
</style>
